/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.ruralLibrary.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.amazonaws.services.s3.model.S3Object;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.admin.api.entity.SysFile;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.file.core.FileProperties;
import com.pig4cloud.pigx.common.file.core.FileTemplate;
import com.pig4cloud.pigx.ruralLibrary.api.entity.CarouselMapEntity;
import com.pig4cloud.pigx.ruralLibrary.mapper.CarouselMapMapper;
import com.pig4cloud.pigx.ruralLibrary.service.CarouselMapService;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.http.Method;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 轮播图
 *
 * @author pig
 * @date 2023-10-18 14:22:46
 */
@Slf4j
@Service
@AllArgsConstructor
public class CarouselMapServiceImpl extends ServiceImpl<CarouselMapMapper, CarouselMapEntity> implements CarouselMapService {

    private final FileTemplate fileTemplate;

    private final FileProperties properties;


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public R uploadFile(MultipartFile file) {
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        Map<String, String> resultMap = new HashMap<>(4);
        resultMap.put("bucketName", properties.getBucketName());
        resultMap.put("fileName", fileName);
        String url = String.format("/ruralLibrary/carouselMap/%s/%s/%s", properties.getBucketName(), "carouselMap", fileName);
        resultMap.put("url", url);

        try (InputStream inputStream = file.getInputStream()) {
            fileTemplate.putObject(properties.getBucketName() + "/carouselMap", fileName, inputStream, file.getContentType());
            // 文件管理数据记录,收集管理追踪文件
        } catch (Exception e) {
            log.error("上传失败", e);
            return R.failed(e.getLocalizedMessage());
        }
        return R.ok(resultMap);
    }

    /**
     * 读取文件
     *
     * @param bucket
     * @param fileName
     * @param response
     */
    @Override
    public void getFile(String bucket, String fileName, HttpServletResponse response) {
        try (S3Object s3Object = fileTemplate.getObject(bucket, fileName)) {
            response.setContentType("application/octet-stream; charset=UTF-8");
            IoUtil.copy(s3Object.getObjectContent(), response.getOutputStream());
        } catch (Exception e) {
            log.error("文件读取异常: {}", e.getLocalizedMessage());
        }
    }

    @Override
    public String getPreviewUrl(String fileName, String bucketName) {
        String endpoint = properties.getOss().getEndpoint();
        String accessKey = properties.getOss().getAccessKey();
        String secretKey = properties.getOss().getSecretKey();
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        if (StringUtils.isNotBlank(fileName)) {

            int startIndex = fileName.indexOf("/lengleng/");
            if (startIndex != -1) {
                String result = fileName.substring(startIndex + "/lengleng/".length());
                try {
                    String objectUrl = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                            .bucket(bucketName)
                            .object(result)
                            .method(Method.GET)
                            //.expiry(60) // 单位秒
                            .expiry(30, TimeUnit.HOURS)
                            .build());
                    return objectUrl;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
